package frank.zou.test.dbunit.base;


import org.dbunit.JdbcBasedDBTestCase;
import org.dbunit.dataset.IDataSet;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;


/**
 * 
 * 
 * @author <a href="mailto:sunjin_sunny@hotmail.com">sunny</a>
 * @version
 * @since 2008-2-25
 * 
 */
public abstract class BaseDAOTestCase extends JdbcBasedDBTestCase {

	private SessionFactory sessionFactory;

	public static ApplicationContext ctx = null;

	static {
		String[] paths = { "src/test/resources/signon-application-context.xml" };
		ctx = new FileSystemXmlApplicationContext(paths);
	}

	public static ApplicationContext getCtx() {
		return ctx;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.dbunit.DatabaseTestCase#setUp()
	 */
	@Override
	protected void setUp() throws Exception {
		super.setUp();
		sessionFactory = (SessionFactory) getBean("sessionFactory");
		Session s = sessionFactory.openSession();
		TransactionSynchronizationManager.bindResource(sessionFactory,
				new SessionHolder(s));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.dbunit.DatabaseTestCase#tearDown()
	 */
	@SuppressWarnings("deprecation")
	@Override
	protected void tearDown() throws Exception {
		super.tearDown();
		SessionHolder holder = (SessionHolder) TransactionSynchronizationManager
				.getResource(sessionFactory);
		Session s = holder.getSession();
		s.flush();
		TransactionSynchronizationManager.unbindResource(sessionFactory);
		SessionFactoryUtils.closeSessionIfNecessary(s, sessionFactory);
	}

	protected Object getBean(String beanName) {
		return ctx.getBean(beanName);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.dbunit.JdbcBasedDBTestCase#getConnectionUrl()
	 */
	@Override
	protected String getConnectionUrl() {
		return PropertiesDBUnitHelper.getInstance().getDBUrl();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.dbunit.JdbcBasedDBTestCase#getDriverClass()
	 */
	@Override
	protected String getDriverClass() {
		return PropertiesDBUnitHelper.getInstance().getDBDriver();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.dbunit.JdbcBasedDBTestCase#getUsername()
	 */
	@Override
	protected String getUsername() {
		return PropertiesDBUnitHelper.getInstance().getUser();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.dbunit.JdbcBasedDBTestCase#getPassword()
	 */
	@Override
	protected String getPassword() {
		return PropertiesDBUnitHelper.getInstance().getPassword();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.dbunit.DatabaseTestCase#getDataSet()
	 */
	@Override
	protected abstract IDataSet getDataSet() throws Exception;
}
